/*
Copyright (c) 2007 Appirio, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class ERController {

static String myLogoUrl = 'https://na1.salesforce.com/img/appExchange145x32.gif';

String currentAccountId = null;
String title = 'Employee Roster';
String logoUrl = myLogoUrl;

String newAccount;


public String getCurrentAccountId() { return currentAccountId; }
public String getMyLogoUrl() { return myLogoUrl; }

public Account[] getMajorAccounts() {  
        return [ select Id, Name, Logo_URL__c from Account where type = 'Customer - Direct' limit 25 ];
}

public String getNewAccount() { return newAccount; }
public void setNewAccount(String nc) { newAccount = nc; }

public Boolean getShowDetail() {
return !( id == selfId);
}

public Boolean getShowMajorAccount() {
return !getShowDetail();
}

public PageReference changeAccount() {
        currentAccountId = newAccount;
        if (currentAccountId == null) {
                return null;
        }
        Account a = [ select Name, Logo_URL__c from Account where Id = :currentAccountId limit 1 ];
        title = 'Major Account: ' + a.Name;
                 
        logoUrl = a.Logo_URL__c;
        // returning a page ref doesn't work properly 'cause this happens on an included (ERHeader) page.
        // the remainder of the body continues un-redirected.
        return null;
}

public String getTitle() { return title; }
public String getLogoURL() { return logoURL; }

// Search
String searchSpec;

public class Contact2 {
        public Contact2(Contact c) {
                id = c.Id; name = c.Name; 
                title = c.Title; 
                department = c.Department; 
                picture = c.Picture_URL__c;
                tags = c.Tags__c == null ? null : c.Tags__c.split(',');
        }
        String id, name, title, department, picture;
        String[] tags;
        public String getId() { return id; }
        public String getPicture() { return picture; }
        public String getName() { return name; }
        public String getDepartment() { return department; }
        public String getTitle() { return title; }
        public String[] getTags() { return tags; }
}

public List<Contact2> getSearchResults() {
        String q = System.currentPageReference().getParameters().get('q');
        String tq = System.currentPageReference().getParameters().get('tq');
        String lq = System.currentPageReference().getParameters().get('lq');
        searchSpec = null;
        currentAccountId = System.currentPageReference().getParameters().get('aid');
        if (q != null) {
        q = '%' + q + '%' ;
        searchSpec = 'Search results - name contains ' + q ; //+ ' ' + currentAccountId;
        
        } else if (tq != null) {
        searchSpec = 'Search results - tag contains ' + tq;
        tq = '%' + tq + '%';
        } else if (lq != null) {
        searchSpec = 'Search results - last name starts with ' + lq;
        lq = lq + '%';
        } else {
        searchSpec = '';
        }

        List<Contact> c = null;
        if (q != null) {
        c = [ select Id, Name, Title, Department, Picture_URL__c, Tags__c from Contact
        where Name like :q and AccountId = :currentAccountId limit 25 ];
        } else if (tq != null) {
        c = [ select Id, Name, Title, Department, Picture_URL__c, Tags__c from Contact
        where Tags__c like :tq and AccountId = :currentAccountId limit 25 ];
        } else if (lq != null) {
        c = [ select Id, Name, Title, Department, Picture_URL__c, Tags__c from Contact
        where LastName like :lq and AccountId = :currentAccountId limit 25 ];
        } else {
        c = [ select Id, Name, Title, Department, Picture_URL__c, Tags__c from Contact
        where AccountId = :currentAccountId limit 25 ];
        }

        List<Contact2> contacts = new List<Contact2>();
        for (Contact contact : c) {
                contacts.add(new Contact2(contact));
        }
        return contacts;
}

public String getSearchSpec() { return searchSpec; }

// Details

String selfId;
String reportsToId;
String id;
public Boolean home = false;
String[] tags;
String newTags = '';
Contact me;

public ERController() {
        id = System.currentPageReference().getParameters().get('id');
        me = null;
        if (id!=null && id.length() >= 15) { 
                id = id.substring(0,15);
                me = [ select Id, AccountId, Tags__c from Contact where Id = :id limit 1];
                if (me != null) {
                        selfId = me.Id;
                        newAccount = me.AccountId;
                        changeAccount();
                } 
        } else  { 
                String aid = System.currentPageReference().getParameters().get('aid');
                if (aid != null && aid.length() >= 15) {
                        aid = aid.substring(0,15);
                        newAccount = aid;
                        changeAccount();
                }
        }
        return;
        
}

public Boolean getSelf() {
        return id.startsWith(selfId);
}

public Boolean getHome() {
        return home;
}

public String getNewTags() { return newTags; }
public void setNewTags(String n) { newTags = n; }

public Contact getContact() {
        Contact c = [ select Id, Description, FirstName, Name, Title, Department, EMail, MailingCity, MailingState, Picture_URL__c,  Tags__c, ReportsTo.Id, ReportsTo.Name from Contact
        where Id = :id ];
        if (c != null) {
                reportsToId = c.ReportsTo.Id;
                tags = c.Tags__c != null ? c.Tags__c.split(',') : null;
        }
        return c;
}

public Contact[] getPeers() {
        return [ select Id, Name, Picture_URL__c from Contact where Id != :id and ReportsToId = :reportsToId and AccountId = :currentAccountId limit 8 ];
}

public Contact[] getReports() {
        return [ select Id, Name, Picture_URL__c from Contact where ReportsToId = :id and AccountId = :currentAccountId limit 8 ];
}

public String[] getTags() {
        return tags;
}

// Tag Cloud

public class Tag {
        Integer weight;
        String value;
        public Tag(Integer pct, String value) {
                if (pct < 13) { weight = 1; }
                else if (pct >= 13 && pct < 26) { weight = 2; }
                else if (pct >= 26 && pct < 38) { weight = 3; }
                else if (pct >= 38 && pct < 51) { weight = 4; }
                else if (pct >= 51 && pct < 63) { weight = 5; }
                else if (pct >= 63 && pct < 76) { weight = 6; }
                else if (pct >= 76 && pct < 88) { weight = 7; }
                else if (pct >= 88) { weight = 8; }
                this.value = value;
        }
        public Integer getWeight() { return weight; }
        public String getValue() { return value; }
}

public List<Tag> getTagCloud() {
        Map<String,Integer> data = new Map<String, Integer>();
        List<Contact> contacts = [ select Tags__c , description from Contact where AccountId = :currentAccountId and Tags__c != '' ];
        Integer max = 0;
        List<String> tagNames = new List<String>();
        for (Contact c : contacts) {
                String[] tags = c.Tags__c.split(',');
                for (String tag : tags) {
                        Integer count = 1;
                        if (data.containsKey(tag)) {
                                count = data.get(tag) + 1;
                        } else {
                                tagNames.add(tag);
                        }
                        data.put(tag, count);
                        if (count > max) {
                                max = count;
                        }       
                }
        }

        // this is convoluted but we can't sort Lists of non-primitives
        tagNames.sort();
        List<Tag> result = new List<Tag>();
        for (String tag : tagNames) {
                result.add(new Tag( (100 * data.get(tag)) / max, tag));
        }
        return result;
}

public PageReference saveTags() {
        PageReference pr = new PageReference('/apex/EmployeeDetail');
        if (newTags == null) {
                return pr;
        }
        String nt = newTags.replace(' ', ',');
        if (me != null) {
                if (me.Tags__c == null) {
                        me.Tags__c = nt;
                } else {
                        me.Tags__c = me.Tags__c + ',' + nt;
                }
                update me;
                newTags = null;
        }
        return pr;
        }
}